package com.mind.core.net.model;

import io.netty.channel.Channel;

import org.apache.log4j.Logger;

import com.mind.core.log.DebugLog;
import com.mind.core.net.constants.INetConstants.ConnectState;
import com.mind.core.net.msg.Message;
import com.mind.db.DaoManager;
import com.mind.db.IDao;
import com.mind.db.IEntity;


public class Connector implements IConnector
{
	protected String id;
	private Channel channel;
	private ConnectState state=ConnectState.STATE_DISCONNECTED;
	private static final Logger logger=Logger.getLogger(Connector.class);
	
	public Channel channel() {
		return channel;
	}
	public void setChannel(Channel channel) {
		this.channel = channel;
		if(channel!=null&&channel.isActive()){
			this.state=ConnectState.STATE_CONNECTED;
		}else{
			this.state=ConnectState.STATE_DISCONNECTED;
		}
	}
     /**
      * 将消息发送给Player
      * 
      * @param msg
      * @throws IllegalArgumentException msg为空的时候会抛出此异常
      * @throws IllegalStateException 与Player绑定的IoSession为空或者没有连接的情况下,会抛出此异常
      */
     @SuppressWarnings("unchecked")
     public void sendMessage(Message msg)
     {
          if(msg == null)
          {
               return;
          }

          if(this.channel == null || !this.channel.isActive())
          {
        	  logger.error("channel is null,player id="+this.id);
               return;
          }
          this.channel.writeAndFlush(msg);
          DebugLog.assertLog(msg.toString());
     }
     @Override
     public boolean closeOnException()
     {
          return true;
     }
	@Override
	public void disconnect() {
		if(this.channel==null){
			logger.error("channel is null,player id="+this.id);
			return;
		}
		this.channel.disconnect();
	}
	@Override
	public void setConnectState(ConnectState state) {
		this.state=state;
	}
	@Override
	public ConnectState getConnectState() {
		return this.state;
	}
	public String id() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	/**此查询仅在Load用户时使用
	 * @param class1
	 * @param id
	 * @return
	 */
	protected IEntity find(Class class1,String id){
		IDao<IEntity> dao= DaoManager.getInstance().getDao(class1);
		if(dao==null){
			logger.error("该表不存在！表="+class1);
			return null;
		}
		IEntity entity=	dao.findOne(id);
		return entity;
	}
}
